package com.likuicat.cataiagentbackend.demo.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import com.likuicat.cataiagentbackend.demo.ApiKey;

import java.io.IOException;

/**
 * 使用HTTP方式调用大模型接口的示例代码
 */
public class HttpAiInvoke {
    
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    private static final String API_KEY = ApiKey.API_KEY; // 从环境变量或配置文件中获取
    
    public static void main(String[] args) throws IOException {
        String response = callDashscopeApi();
        System.out.println("API响应: " + response);
    }
    
    public static String callDashscopeApi() {
        // 构建请求数据
        JSONObject requestData = new JSONObject();
        requestData.set("model", "qwen-plus");
        
        JSONObject input = new JSONObject();
        JSONObject[] messages = new JSONObject[2];
        
        // 系统消息
        JSONObject systemMessage = new JSONObject();
        systemMessage.set("role", "system");
        systemMessage.set("content", "You are a helpful assistant.");
        messages[0] = systemMessage;
        
        // 用户消息
        JSONObject userMessage = new JSONObject();
        userMessage.set("role", "user");
        userMessage.set("content", "你好？");
        messages[1] = userMessage;
        
        input.set("messages", messages);
        requestData.set("input", input);
        
        // 参数配置
        JSONObject parameters = new JSONObject();
        parameters.set("result_format", "message");
        requestData.set("parameters", parameters);
        
        // 发送 HTTP 请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .body(requestData.toString())
                .timeout(30000) // 30秒超时
                .execute();
        
        if (response.isOk()) {
            return response.body();
        } else {
            throw new RuntimeException("API请求失败: " + response.getStatus() + " - " + response.body());
        }
    }
}